package com.example.front.serivce;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.LineDto;
import com.example.front.entity.Craft;
import com.example.front.entity.Line;
import com.example.front.entity.Workshop;
import com.example.front.mapper.LineMapper;
import com.example.passport.entity.User;
import com.example.passport.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LineService {
    @Resource
    LineMapper lineMapper;
    @Resource
    UserService userService;
    @Resource
    WorkshopService workshopService;
    @Resource
    BoxService boxService;
    @Resource
    CraftService craftService;

    /**
     * 添加产线
     */
    public void createLine(Line line) {
        List<Line> list = new ArrayList<>();
        if (!Objects.equals(lineMapper.findLineByName(line), list)) {
            throw new BusinessException("名称已存在");
        }
        userService.findUserById(line.getUserId());
        workshopService.findById(line.getWorkshopId(), line.getTenantId());

        lineMapper.create(line);
    }

    /**
     * 删除产线
     */
    @Transactional
    public void deleteLine(long tenantId, Long id) {
        Line line = Line.builder().
                tenantId(tenantId).
                id(id).build();
        craftService.deleteCraftByLineId(id);
        if (boxService.findByLineId(tenantId, id) != 0) {
            throw new BusinessException("该产线下存在有按钮盒，请将该产线下的按钮盒删除或修改再执行该操作");
        }
        int i = lineMapper.delete(line);
        if (i == 0) {
            throw new BusinessException("删除失败");
        }
    }

    /**
     * 产线信息修改
     */
    public void updateLine(Line line) {
        if (lineMapper.findByName(line) != null) {
            throw new BusinessException("名称已存在");
        }
        userService.findUserById(line.getUserId());
        if (lineMapper.update(line) == 0) {
            throw new BusinessException("操作异常");
        }
    }

    /**
     * 列出产线列表
     */
    public ListDto<LineDto> listLine(Line condition, Pagination pagination) {
        ListDto<LineDto> list = new ListDto<>();
        // 获取总数
        long total = lineMapper.count(condition);
        // 如果总数为0则直接返回
        if (total == 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }
        pagination.setTotal(total);

        // 获取产线列表并转成Dto
        List<LineDto> lineDtos = new ArrayList<>();
        List<Line> lines = lineMapper.findAll(condition, pagination);
        for (Line line : lines) {
            LineDto lineDto = new LineDto();
            BeanUtils.copyProperties(line, lineDto); // 转dto
            lineDtos.add(lineDto);
        }

        // 获取产线管理员ids
        List<Long> userIds = lines.stream().map(Line::getUserId)
                .distinct()
                .collect(Collectors.toList());
        //车间
        List<Long> workshopIds = lines.stream().map(Line::getWorkshopId)
                .distinct()
                .collect(Collectors.toList());

        // 获取产线管理员的信息
        Map<Long, User> userMap = lineMapper.findUserByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        //车间
        Map<Long, Workshop> workshopMap = lineMapper.findWorkshopByIds(workshopIds).stream()
                .collect(Collectors.toMap(Workshop::getId, workshop -> workshop));

        // 设置产线管理员的名称
        for (LineDto lineDto : lineDtos) {
            User user = userMap.get(lineDto.getUserId());
            if (user != null) {
                lineDto.setUserName(user.getName());
            }
            //车间
            Workshop workshop = workshopMap.get(lineDto.getWorkshopId());
            if (workshop != null) {
                lineDto.setWorkshopName(workshop.getName());
            }

            Craft craft = new Craft();
            craft.setLineId(lineDto.getId());
            craft.setTenantId(lineDto.getTenantId());
            long count = craftService.count(craft);
            lineDto.setCraftNum(count);
        }

        // 组装数据
        list.setPagination(pagination);
        list.setList(lineDtos);
        return list;
    }

    /**
     * 获取产线信息
     */
    public Map<Long, Line> findByIds(List<Long> lineIds) {

        Map<Long, Line> lineMap = lineMapper.findLineByIds(lineIds).stream()
                .collect(Collectors.toMap(Line::getId, line -> line));

        return lineMap;
    }

    /**
     * 查找产线
     */
    public Line findById(Long id, Long tenantId) {
        Line line = lineMapper.findLineById(tenantId, id);
        if (line == null) {
            throw new BusinessException("产线不存在");
        }
        return line;

    }

    /**
     * 查找产线
     */
    public Line findById(Long id) {
        Line line = lineMapper.findLineByID(id);
//        if (line == null) {
//            throw new BusinessException("产线不存在");
//        }
        return line;
    }

    /**
     * 通过车间查找产线
     */
    public long findByWorkshopId(Long id, Long tenantId) {

        return lineMapper.findByWorkshopId(id, tenantId);
    }
}
